package com.major;

import com.major.Server;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

public class HttpUtil {

    /**
     * html ---> 响应
     *
     * @param html
     * @return
     */
    /*public static byte[] getResponse(String html) {
        return ("http/1.1 200 ok\r\nContent-Type: text/html;charset=utf-8\r\nContent-Length: "
                + html.getBytes().length + "\r\n\r\n" + html).getBytes();
    }*/

    /**
     * 使用流获得页面字符串
     *
     * @param url 路径
     * @return 页面字符串
     * @throws IOException
     */
    public static String getPage(String url) {
        StringBuilder builder = new StringBuilder();

        if ("".equals(url) || "/".equals(url) || url == null){
            url = "index.html";
        }

        // 得到绝对的父路径
        String path = Server.class.getProtectionDomain().getCodeSource().getLocation().getPath();

        path = path.substring(0, path.lastIndexOf("/")) + "/pages/";


        InputStream resource = null;

        try {
            resource = new FileInputStream(path + url);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            // 找不到就报404
            try {
                resource = new FileInputStream(path + "404.html");
            } catch (FileNotFoundException fileNotFoundException) {
                fileNotFoundException.printStackTrace();
            }
        }

        byte[] buf = new byte[1024];
        int len;
        try {
            while ((len = resource.read(buf)) != -1) {
                builder.append(new String(buf, 0, len));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

//            String name = "李四";
//            String res = builder.toString().replace("{{ name }}", name);

        return builder.toString();
    }
}
